package com.my.java.common;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class PropertyUtil {
    
    private static Logger logger = LoggerFactory.getLogger(PropertyUtil.class);

    private static Properties props;

    static {
        loadProps();
    }
    
    /**
     * 读取方法（同一时刻最多只有一个线程执行）
     */
    synchronized static private void loadProps() {
        logger.info("start loader properties");
        props = new Properties();
        InputStream in = null;
        try {
            //通过类加载器进行获取properties文件流-->
            in = PropertyUtil.class.getClassLoader().getResourceAsStream("config.properties");
            //第二种，通过类进行获取properties文件流-->
            //in = PropertyUtil.class.getResourceAsStream("/config.properties");
            props.load(in);
        } catch (Exception e) {
            logger.error("NO File");
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error("File Exception");
            }
        }
        //logger.info("properties-ok");
    }
    
    /**
     * 根据key获取value
     * @param key
     * @return
     */
    public static String getValue(String key) {
        if (null == props) {
            loadProps();
        }
        return props.getProperty(key);
    }

    
    public static String getProperty(String key, String defaultValue) {
        if (null == props) {
            loadProps();
        }
        return props.getProperty(key, defaultValue);
    }
}